const bodyParser = require("body-parser");
const app = require("express")();
const fs = require("fs");
const dayjs = require("dayjs");
const path = require("path");
const LOGDIR = path.resolve(process.cwd(), "./log");

app.use(bodyParser.json());
app.post("/handleError", (req, res) => {
  const todayFile = dayjs().format("YYYY-MM-DD") + ".log";
  const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const filePath = path.join(LOGDIR, todayFile);
  const { message, stack, hook } = req.body;
  const isHasFile = fs.existsSync(filePath);
  hasDir(LOGDIR);
  const str = `钩子函数：${hook}
错误信息：${message}
错误位置：${stack}  
时间：${now}\n\n`;
  const dealFn = isHasFile ? fs.appendFileSync : fs.writeFileSync;
  dealFn(filePath, str, "utf8");
  res.send("ok");
});

function hasDir(dir) {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }
  return dir;
}
module.exports = app;
